<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="paperName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="试卷状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷名称" align="center" prop="paperName" />
      <el-table-column label="考试时长" align="center" prop="duration" width="100">
        <template #default="scope">
          <span class="duration-tag">{{ scope.row.duration }} 分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template #default="scope">
          <span class="time-tag">{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="160">
        <template #default="scope">
          <span class="time-tag">{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="题目数量" align="center" prop="number" width="100">
        <template #default="scope">
          <span class="count-tag">{{ scope.row.number || 0 }} 题</span>
        </template>
      </el-table-column>
      <el-table-column label="总分" align="center" prop="totalScore" width="80">
        <template #default="scope">
          <span class="score-tag">{{ scope.row.totalScore || calculateTotalScore(scope.row) }}分</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">草稿</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">进行中</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">已结束</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 答题按钮 - 状态为发布才显示 -->
          <el-button
            v-if="scope.row.status === 1"
            type="primary"
            link
            icon="Edit"
            @click="enterAnswer(scope.row)"
          >答题</el-button>
          <!-- 查看成绩按钮 -->
          <el-button
            type="success"
            link
            icon="DataAnalysis"
            @click="viewScore(scope.row)"
          >查看成绩</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { listPaper } from '@/api/manage/paper';
import useUserStore from '@/store/modules/user';
import { useRouter } from 'vue-router';
import { getStudentByNumber } from '@/api/manage/student';

const router = useRouter();
const loading = ref(false);
const total = ref(0);
const paperList = ref([]);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  paperName: undefined,
  status: undefined // 默认不限制状态
});
const showSearch = ref(true);
const userStore = useUserStore();
const classIds = ref([]);

// 状态选项
const statusOptions = [
  { value: 1, label: '进行中' },
  { value: 2, label: '已结束' }
];

// 查询试卷列表
const getList = () => {
  loading.value = true;
  
  // 更新查询参数
  const query = {
    ...queryParams,
    classId: classIds.value.length > 0 ? classIds.value.join(',') : undefined
  };
  
  // 如果未指定状态，只查询状态为1或2的试卷
  if (!query.status) {
    // 不在查询参数中添加数组，前端过滤处理
    // 避免后端参数转换错误
  } else {
    // 确保传递的是单个整数值，而不是逗号分隔的字符串
    query.status = parseInt(query.status);
  }
  
  listPaper(query).then(response => {
    // 前端过滤非草稿状态的试卷（状态为1或2）
    paperList.value = response.rows.filter(paper => paper.status === 1 || paper.status === 2);
    total.value = paperList.value.length;
    loading.value = false;
  }).catch((error) => {
    console.error('加载试卷列表出错:', error);
    loading.value = false;
    ElMessage.error('加载试卷列表失败');
  });
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.paperName = undefined;
  queryParams.status = undefined; // 重置状态条件
  queryParams.pageNum = 1;
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  // 可根据需要处理多选逻辑
};

// 进入答题页面
const enterAnswer = (row) => {
  // 检查试卷状态
  if (row.status !== 1) {
    ElMessage.warning('只能参加正在进行中的考试');
    return;
  }
  
  // 跳转到答题页面
  router.push({
    path: '/answer/index',
    query: { paperId: row.paperId || row.paper_id }
  });
};

// 查看成绩
const viewScore = async (row) => {
  try {
    // 获取试卷ID
    const paperId = row.paperId || row.paper_id;
    
    console.log('查看成绩，试卷ID:', paperId);
    
    // 跳转到成绩查看页面，只传递试卷ID
    router.push({
      path: '/manage/score/index',
      query: {
        paperId: paperId
      }
    });
  } catch (error) {
    console.error('查看成绩出错:', error);
    ElMessage.error('操作失败，请重试');
  }
};

// 初始化时获取用户信息和班级列表
onMounted(async () => {
  try {
    loading.value = true;
    
    // 获取用户信息
    const userInfo = await userStore.getInfo();
    
    // 初始化班级ID
    if (userStore.roles.includes('admin')) {
      // 管理员可以查看所有试卷
      classIds.value = [];
    } else {
      // 学生只能看到自己班级的试卷
      if (userInfo && userInfo.user && userInfo.user.userName) {
        // 获取学生所在班级
        const studentInfo = await getStudentInfo(userInfo.user.userName);
        if (studentInfo && studentInfo.classId) {
          classIds.value = [studentInfo.classId];
          console.log('学生所在班级ID:', classIds.value);
        } else {
          console.log('未找到学生班级信息');
        }
      } else {
        console.log('获取用户信息失败或用户信息不完整');
      }
    }
    
    // 查询试卷列表
    getList();
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('加载试卷列表失败');
  } finally {
    loading.value = false;
  }
});

// 获取学生信息
const getStudentInfo = async (studentNumber) => {
  try {
    // 调用后端API获取学生信息
    const res = await getStudentByNumber(studentNumber);
    if (res.code === 200 && res.data) {
      console.log('获取到学生信息:', res.data);
      return res.data;
    }
    return null;
  } catch (error) {
    console.error('获取学生信息失败:', error);
    return null;
  }
};

// 添加计算总分的函数
const calculateTotalScore = (paper) => {
  if (!paper) return 0;
  
  // 如果已有总分，直接返回
  if (paper.totalScore) {
    return parseFloat(paper.totalScore).toFixed(1);
  }
  
  // 如果没有总分，根据题目数量和默认分值计算
  let totalScore = 0;
  
  // 尝试从题目中计算
  if (paper.questions && paper.questions.length > 0) {
    // 从questions字段计算总分
    paper.questions.forEach(q => {
      if (q.questionScore) {
        totalScore += parseFloat(q.questionScore);
      }
    });
  }
  
  // 如果没有计算出总分，返回默认值
  if (totalScore === 0) {
    return '0.0';
  }
  
  return totalScore.toFixed(1);
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.time-tag {
  color: #85ce61;
  font-weight: bold;
  display: inline-block;
  padding: 2px 6px;
  background-color: #f0f9eb;
  border-radius: 4px;
  border: 1px solid #85ce61;
  font-size: 12px;
}

.count-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #f0f2f5;
  border: 1px solid #909399;
  border-radius: 4px;
  color: #606266;
  font-weight: bold;
  font-size: 12px;
}

.score-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-weight: bold;
  font-size: 12px;
}
.duration-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #eee5f9;
  border: 1px solid #7d21ee;
  border-radius: 4px;
  color: #7d21ee;
  font-weight: bold;
  font-size: 12px;
}
</style>
